﻿using DevExpress.ExpressApp.ApplicationBuilder;
using DevExpress.ExpressApp.Blazor.ApplicationBuilder;
using DevExpress.ExpressApp.Blazor.Services;
using DevExpress.ExpressApp.ConditionalAppearance;
using DevExpress.ExpressApp.Validation.Blazor;
using EasyXaf.EntityDesigner.Services;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.SignalR;

namespace EasyXaf.EntityDesigner;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(typeof(HubConnectionHandler<>), typeof(ProxyHubConnectionHandler<>));

        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddHttpContextAccessor();
        services.AddScoped<CircuitHandler, CircuitHandlerProxy>();
        services.AddXaf(Configuration, builder =>
        {
            builder.UseApplication<EntityDesignerBlazorApplication>();
            builder.Modules
                .Add<ConditionalAppearanceModule>()
                .Add<ValidationBlazorModule>()
                .Add<EntityDesignerBlazorModule>();
            builder.ObjectSpaceProviders
                .AddXpo((serviceProvider, options) =>
                {
                    var dbFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DomainModel.db");
                    var connectionString = $"XpoProvider=SQLite;Data Source=\"{dbFile}\"";
                    options.ConnectionString = connectionString;
                    options.ThreadSafe = true;
                    options.UseSharedDataStoreProvider = true;
                })
                .AddNonPersistent();
        });

        services.Configure<DesignerOptions>(options =>
        {
            options.Home = Configuration.GetValue<string>("Kestrel:Endpoints:Http:Url");
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseRequestLocalization();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseXaf();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapXafEndpoints();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
            endpoints.MapControllers();
        });
    }
}
